package com.ai3d.rfid.base.activity

import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.view.Window
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.ai3d.rfid.base.vm.BaseViewModel
import com.ai3d.rfid.common.log.Logcat
import com.ai3d.rfid.ext.getVmClazz
import com.ai3d.rfid.ext.utils.notNull
import com.ai3d.rfid.network.manager.NetworkStateManager
import com.bj.ski.base.R
import com.bj.ski.base.common.statusbar.StatusBarCompat

/**
 *Base activity injected with ViewModel
 */
abstract class BaseVmActivity<VM : BaseViewModel> : AppCompatActivity() {

    lateinit var mViewModel: VM

    abstract fun layoutId(): Int

    abstract fun initView(savedInstanceState: Bundle?)

    abstract fun showLoading(message: String = "请求网络中...")

    abstract fun dismissLoading()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE)
        initDataBind().notNull({
            Logcat.d("not null")
            setContentView(it)
        }, {
            Logcat.d("")
            setContentView(layoutId())
        })
        init(savedInstanceState)
    }

    private fun init(savedInstanceState: Bundle?) {
        mViewModel = createViewModel()
        registerUiChange()
        initView(savedInstanceState)
        createObserver()
        NetworkStateManager.instance.mNetworkStateCallback.observe(this, Observer {
            onNetworkStateChanged(it)
        })
    }

    /**
     * monitoring network changes,subclass should override it
     */
    open fun onNetworkStateChanged(netState: Boolean) {}

    /**
     *creation of viewModel
     */
    private fun createViewModel(): VM {
        return ViewModelProvider(this).get(getVmClazz(this))
    }

    /**
     * creation of LiveData observer
     */
    abstract fun createObserver()

    /**
     *Register UI events
     */
    private fun registerUiChange() {
        //显示弹窗
        mViewModel.loadingChange.showDialog.observe(this, Observer {
            showLoading(it)
        })
        //关闭弹窗
        mViewModel.loadingChange.dismissDialog.observe(this, Observer {
            dismissLoading()
        })
    }

    /**
     * 将非该Activity绑定的ViewModel添加 loading回调 防止出现请求时不显示 loading 弹窗bug
     * @param viewModels Array<out BaseViewModel>
     */
    protected fun addLoadingObserve(vararg viewModels: BaseViewModel) {
        viewModels.forEach { viewModel ->
            //显示弹窗
            viewModel.loadingChange.showDialog.observe(this, Observer {
                showLoading(it)
            })
            //关闭弹窗
            viewModel.loadingChange.dismissDialog.observe(this, Observer {
                dismissLoading()
            })
        }
    }

    /**
     * 供子类BaseVmDbActivity 初始化Databinding操作
     */
    open fun initDataBind(): View? {
        return null
    }

    override fun setContentView(view: View?) {
        super.setContentView(view)
        translucentStatusBar()
    }

    override fun setContentView(layoutResID: Int) {
        super.setContentView(layoutResID)
        translucentStatusBar()
    }

    private fun translucentStatusBar() {
        StatusBarCompat.translucentStatusBar(this, true)
        if (isLightColor(resources.getColor(R.color.purple_200))) {
            StatusBarCompat.changeToLightStatusBar(this)
        } else {
            StatusBarCompat.cancelLightStatusBar(this)
        }
    }

    private fun isLightColor(color: Int): Boolean {
        val darkness =
            1 - (0.299 * Color.red(color) + 0.587 * Color.green(
                color
            ) + 0.114 * Color.blue(color)) / 255
        return if (darkness < 0.5) {
            true // It's a light color
        } else {
            false // It's a dark color
        }
    }
}